import ky from 'ky'

export default ky.create({
  prefixUrl: '',
  timeout: 6000,
  retry: 1,
  throwHttpErrors: false,
  hooks: {
    beforeRequest: [
      (request) => {
        const token = localStorage.getItem('token') || ''
        request.headers.set('token', token)
      },
    ],
    afterResponse: [
      async (_request, _options, response) => {
        if (response.status == 401) {
          // 同步服务端登录状态失效
          // vue-router和store还没有初始化暂时不能用
          localStorage.removeItem('token')
          localStorage.setItem('pre_path', location.pathname)
          window.location.href = '/login'
          return response
        }
        else {
          // 服务端把错误直接在http协议层进行封装
          // 为了磨平http协议和自定义通信协议的数据返回结构进行处理
          // const body = await response.json()
          // return new Response(JSON.stringify(body), { status: 200 })
          // console.log(response)
          return response
        }
      },
    ],
  },
})
